package com.example.demo.service;

import com.example.demo.dao.UserMapper;
import com.example.demo.pojo.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class UserService {
    private UserMapper userMapper;

    public UserService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    // 从缓存或数据库中获取用户
    @Cacheable(value = "users", key = "#id")  // 缓存查询结果，key使用用户的id
    public Optional<User> getUserById(Long id) {
        System.out.println("缓存查询结果...");
        return userMapper.findById(id);
    }

    // 更新用户，更新缓存
    @CachePut(value = "users", key = "#user.id")  // 更新缓存，缓存的key是用户的id
    public User updateUser(User user) {
        System.out.println("更新缓存...");
        return userMapper.save(user);  // 保存更新后的用户
    }

    // 清除缓存
    @CacheEvict(value = "users", key = "#id")  // 根据id清除缓存
    public void clearCache(Long id) {
        System.out.println("根据id清除缓存 " + id);
    }

    // 清除所有缓存
    @CacheEvict(value = "users", allEntries = true)  // 清除所有缓存
    public void clearAllCache() {
        System.out.println("清除所有缓存");
    }
}
